//
//  VideoView.m
//  播放器模拟(列表)
//
//  Created by lanou3g on 15/11/2.
//  Copyright © 2015年 songhaowen. All rights reserved.
//
void *LSPlayer =&LSPlayer;
#import "VideoView.h"
#import "MBProgressHUD+MJ.h"

@interface VideoView ()



@end

@implementation VideoView

- (void)setContentUrl:(NSString *)contentUrl
{
    _contentUrl = contentUrl;
    
    NSURL *videoUrl = [NSURL URLWithString:contentUrl];
    // 1. 用 url 初始化一个 AVAsset (可用 playerItemWithUrl 代替)
    AVAsset *videoAsset = [AVURLAsset assetWithURL:videoUrl];
    [self setAsset:videoAsset];
}

- (void)setAsset:(AVAsset *)asset
{
    // 初始化 AVPlayerItem
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
    self.playerItem = playerItem;
    
    // 2. 用 AVPlayerItem 初始化 AVPlayer
    AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
    self.player = player;
    
    // 3. 利用 AVPlayer 初始化 AVPlayerLayer
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    // 设置模式
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    self.playerLayer.frame = self.frame;
    
    // 4. 将 AVPlayerLayer 添加到 layer层
    [self.layer addSublayer:self.playerLayer];
    
    
    // 监听 AVPlayerItem 的状态
    [_player addObserver:self forKeyPath:@"rate" options:NSKeyValueObservingOptionNew context:LSPlayer];
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];// 监听loadedTimeRanges属性
    // 添加监听者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
}

#pragma mark ---observeValueForKeyPath
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    
    if ([keyPath isEqualToString:@"status"]) {
        
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            
            NSLog(@"ready to play");
            
            [MBProgressHUD hideHUD];
            
            // 可以播放先暂停
            [_player pause];
            _playState = VideoPlayerPlaybackStatePaused;
            
            _timeScale = playerItem.currentTime.timescale;
            // 1. 获取 playItem 的总时间
            CMTime duration = _player.currentItem.duration;
            self.totalTime = CMTimeGetSeconds(duration);
            
            // 可以播放
            if ([_delegate respondsToSelector:@selector(canStartPlaying:)])
            {
                [_delegate canStartPlaying:self];
            }
            _playState = VideoPlayerPlaybackStatePaused;
            // 这里可以传总时间出去
            
            // 2. 可以播放就开始监听播放进度
            [self monitoringPlayback:_player.currentItem];
            
        } else if ([playerItem status] == AVPlayerStatusFailed) {
            NSLog(@"play failed");
            
            if ([_delegate respondsToSelector:@selector(dontPlayer:)])
            {
                [_delegate dontPlayer:self];
            }
            
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        
        
        // 这里可传缓存进度出去
        NSTimeInterval timeInterval = [self availableDuration];
        if ([_delegate respondsToSelector:@selector(bufferTimeLength:)])
        {
            [_delegate bufferTimeLength:timeInterval];
        }
        
        
        
        
        int rate = [[NSString stringWithFormat:@"%f", _player.rate] intValue];
        if (rate == 0) {
            NSLog(@"网络不好");
            [_player pause];
            float ti = [[NSString stringWithFormat:@"%f", timeInterval] floatValue];
            if (ti > _currentTime + 20) {
                NSLog(@"播放--------");
            }
        }
    }
    
}

- (NSTimeInterval)availableDuration
{
    NSArray *loadedTimeRanges = [[_player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;
#warning startSeconds会随着滑块的改变而改变
    NSLog(@"%f----%f-----%f", startSeconds, durationSeconds, result);
    return result;
}

- (void)monitoringPlayback:(AVPlayerItem *)playerItem
{
    
    __weak typeof(self) weakSelf = self;
    self.obj = [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time)
    {
        
        CGFloat currentSecond = playerItem.currentTime.value / playerItem.currentTime.timescale;
        _currentTime = currentSecond;
        if ([weakSelf.delegate respondsToSelector:@selector(currentPlayerTimeLength:)])
        {
            [weakSelf.delegate  currentPlayerTimeLength:currentSecond];
        }
                   
    }];
    
    if (self.obj) {
        return;
    }
    
}

- (void)moviePlayDidEnd:(NSNotification *)notification
{
    _playState = VideoPlayerPlaybackStateStopped;
    
    if ([_delegate respondsToSelector:@selector(playEnd:)])
    {
        [_delegate playEnd:self];
    }
}

- (void)speed:(CMTime)speedTime
{
    
    [_player.currentItem seekToTime:speedTime];
    
}



@end
